<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<input type="text" name="message" autocomplete="off">
<button>发送</button>
<!--通话列表-->
<ul id="history">
</ul>

<script>
    const message_inp = document.querySelector('input[name=message]');
    const send_btn = document.querySelector('button');
    const history = document.querySelector('#history');

    // 原生websocket
    ws = new WebSocket('ws://127.0.0.1:8088/api')

    // 客户端主动发送数据
    send_btn.onclick = () =>{
        //使用websocket发送数据
        let username = '用户A';
        let message = message_inp.value;
        ws.send(JSON.stringify({
            username,
            message
        }))

        history.innerHTML += `<li style="text-align:left">${username}:${message}</li>`
    }

    // 客户端监听服务端主动发送的数据
    ws.onmessage = (message)=>{
        console.log('接受到服务端推送的数据：', message.data)
        history.innerHTML += `<li style="text-align:right">${message.data}:ChatGPT</li>`
    }

</script>
</body>
</html>